package com.hui.excel.web;

import com.hui.auth.dto.JsonResult;
import com.hui.auth.entity.AuthUser;
import com.hui.excel.service.ExcelService;
import com.hui.excel.util.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 系统用户管理
 * Created by LiaoYunHui on 2017/9/29/029.
 */
@Api(tags = "Excel管理")
@RestController
@RequestMapping(value = "excel")
public class ExcelController {

    @Autowired
    private ExcelService excelService;

    /**
     * 批量新增用户
     */
    @ApiOperation(value = "批量新增用户")
    @PostMapping(value = "batch_insert_user")
    public JsonResult insert(MultipartFile file, String name) throws Exception {
        JsonResult jsonResult = new JsonResult();
        StringBuilder returnMsg = new StringBuilder();
        List<AuthUser> userList = new ArrayList<>();
        int index = 1;
        int count = 0;
        int error = 0;
        int success = 0;
        //判断文件类型
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        Assert.isTrue("xlsx".equals(suffix), "文件类型不匹配");
        //读取Excel数据内容
        List<Map<Integer, String>> list = ExcelUtil.readExcelContentToList(file.getInputStream());
        //批量导入客户信息
        try {
            count = list.size();
            for (Map<Integer, String> map : list) {
                if (map.get(0) == null || "".equals(map.get(0))) {
                    returnMsg.append("第").append(index).append("行：【客户简称(必填)】列不能为空;");
                } else if (map.get(1) == null || "".equals(map.get(1))) {
                    returnMsg.append("第").append(index).append("行：【客户全称(必填)】列不能为空;");
                } else {
                    AuthUser user = new AuthUser();
                    userList.add(user);
                    success++;
                }
            }
            excelService.batchInsert(userList);
            error = count - success;
            returnMsg.append("\ncount：").append(count);
            returnMsg.append("\nerror：").append(error);
            returnMsg.append("\nsuccess：").append(success);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jsonResult.setMsg(returnMsg.toString());
    }
}
